/**
 * 
 */
package be.redo.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Repository;

import be.redo.model.entities.Payment;
import be.redo.model.entities.Vacation;

/**
 * @author Frank
 * 
 */
@Repository
public class PaymentDAOImpl implements PaymentDAO {
	private EntityManager entityManager;

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	/**
	 * @see be.redo.dao.PaymentDAO#create(be.redo.model.entities.Payment)
	 */
	@Override
	public void create(Payment instance) {
		try {
			entityManager.persist(instance);
		} catch (RuntimeException ex) {
			entityManager.clear();
			throw ex;
		}
	}

	/**
	 * @see be.redo.dao.PaymentDAO#read(long)
	 */
	@Override
	public Payment read(long id) {
		return entityManager.find(Payment.class, id);
	}

	/**
	 * @see be.redo.dao.PaymentDAO#update(be.redo.model.entities.Payment)
	 */
	@Override
	public void update(Payment instance) {
		try {
			entityManager.merge(instance);
			entityManager.flush();
		} catch (RuntimeException ex) {
			entityManager.clear();
			throw ex;
		}
	}

	/**
	 * @see be.redo.dao.PaymentDAO#delete(long)
	 */
	@Override
	public void delete(long id) {
		Payment instance = entityManager.find(Payment.class, id);
		if (instance != null) {
			entityManager.remove(instance);
			entityManager.flush();
		}
	}

	/**
	 * @see be.redo.dao.PaymentDAO#findAll()
	 */
	@Override
	public List<Payment> findAll() {
		TypedQuery<Payment> query = entityManager.createNamedQuery(
				"findAllPayments", Payment.class);
		return query.getResultList();
	}

	/**
	 * @see be.redo.dao.PaymentDAO#count()
	 */
	@Override
	public int count() {
		TypedQuery<Number> query = entityManager.createNamedQuery(
				"findAantalPayments", Number.class);
		return (query.getSingleResult()).intValue();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * be.redo.finders.PaymentFinders#findPaymentsByVacation(be.redo.model.Vacation
	 * )
	 */
	@Override
	public List<Payment> findPaymentsByVacation(Vacation vacation) {
		TypedQuery<Payment> query = entityManager.createNamedQuery(
				"findPaymentsByVacation", Payment.class);
		query.setParameter("vacation", vacation);
		return query.getResultList();
	}

}
